package com.phoenix.jsef.jdbcutils;


import com.phoenix.jsef.common.CUtils;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @version v1.0
 * @classname: resolvedsqltemplate
 * @description:todo(解析从资源文件中待执行的sql语句)
 * @author: 李启联
 * @date: 2018-04-24 15:52
 * @copyright: copyright (c), 2018-2018
 * 申明：本内容未经作者本人同意,禁止外泄以及用于其他的商业项目.
 */
public class ResolveSqlTemplate {

    private static final Pattern pattern = Pattern.compile("\\{(.*?)\\}");
    private static Matcher matcher;

    /**
     * 解析sql模板内容，转换成可以被数据库执行的sql语句。<br/>
     * ${}的内容被原样替换;#{}的内容被替换为"?"占位
     * @param sql sql模板内容
     * @param params 外部提供的参数,以Map<KEY,VALUE>的形式提供
     * @return
     */
    public static ResolvedSqlResult resolveSql(String sql, Map<String,Object> params) {
        ResolvedSqlResult  result = new ResolvedSqlResult();
        LinkedList<Object> paramsList = new LinkedList<>();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            paramsList.add(entry.getValue());
        }
        Set<String> descSet = new HashSet<>();

        String key = null,keyclone= null,parm_value = null,result_sql = sql,desc="";
        matcher = pattern.matcher(sql);
        while (matcher.find()) {
            key = matcher.group();
            keyclone = key.substring(1, key.length() - 1).trim();
            if(!CUtils.mapContainsLikeKey(params,keyclone)){
                descSet.add("所需的参数:"+keyclone+" 未提供\n");
            }
            parm_value = CUtils.getValueFromMapByLikeKey(keyclone,params)==null ? "" : CUtils.getValueFromMapByLikeKey(keyclone,params).toString().trim();
            //先替换带${}形式的占位参数
            sql= sql.replace("$"+key,"'"+parm_value+"'");
        }
        if(descSet.size() > 0){//如果有参数未提供
            result.setResultCode(ResolvedCodeType.Fail);
            Iterator<String> it = descSet.iterator();
            while (it.hasNext()){
                desc = desc + it.next();
            }
            result.setResultDesc(desc);
            result.setResultSqlScript(result_sql);
            result.setParams(paramsList.toArray());
            return result;
        }

        paramsList.clear();
        matcher = pattern.matcher(sql);
        while (matcher.find()) {
            key = matcher.group();
            keyclone = key.substring(1, key.length() - 1).trim();
            parm_value = CUtils.getValueFromMapByLikeKey(keyclone,params).toString().trim();
            paramsList.add(parm_value);
            sql= sql.replace("#"+key,"?");
        }

        result.setResultCode(ResolvedCodeType.Success);
        result.setResultDesc("解析SQL模板成功");
        result.setResultSqlScript(sql);
        result.setParams(paramsList.toArray());
        return result;
    }


    /**
     * 重写resolveSql方法
     * @param sqlFileName  sql模板名称
     * @param sqlFilePrefix sql模板文件路径前缀
     * @param sqlFileSuffix sql模板文件路径后缀
     * @param params 准备替换的参数
     * @return ResolvedSqlResult对象
     * @throws Exception
     */
    public static ResolvedSqlResult resolveSql(String sqlFileName,String sqlFilePrefix,String sqlFileSuffix,Object... params) throws Exception {
        int params_len = params.length;
        if(sqlFilePrefix.endsWith("/"))
            sqlFilePrefix = sqlFilePrefix.substring(0,sqlFilePrefix.length() -1);

        String resourceFilePath = sqlFilePrefix+"/"+sqlFileName+sqlFileSuffix;
        String sql = CUtils.loadClassPathResourceFileToString(resourceFilePath);

        if(params_len == 1 && (params[0] instanceof Map )){
            return resolveSql(sql,(Map)params[0]);
        }else{
            return  new ResolvedSqlResult(ResolvedCodeType.Success,"解析SQL模板成功",sql,null);
        }

        //return null;
    }

}
